package com.hui.server.controller;


import com.hui.server.entity.Admin;
import com.hui.server.service.AdminService;
import com.hui.server.service.RoleService;
import com.hui.server.util.Result;
import com.sun.net.httpserver.HttpsConfigurator;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;

/**
 * <p>
 * 前端控制器
 * </p>
 *              操作员，可以理解为管理员
 * @author hui
 * @since 2022-03-31
 */
@RestController
@RequestMapping("/system/admin")
@Slf4j
public class AdminController {

    private final AdminService adminService;

    private final RoleService roleService;

    @Autowired
    public AdminController(AdminService adminService, RoleService roleService) {
        this.adminService = adminService;
        this.roleService = roleService;
    }



    @ApiOperation("模糊查询所有操作员，注意：SpringSecurity会带有权限、是否过时等字段信息，以后可以通过定义 VO 层返回")
    @GetMapping("/")
    public Result<?> getAllAdminsByFuzzyQuery(String keywords) {
     return adminService.getAllAdminsByFuzzyQuery(keywords);
    }


    @ApiOperation("更新操作员")
    @PutMapping("/")
    public Result<?> updateAdmin(@RequestBody Admin admin){
        boolean update = adminService.updateById(admin);
        return update?
                Result.success("更新成功！"):
                Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()),"更新失败！");

    }

    @ApiOperation("删除操作员")
    @DeleteMapping("/{id}")
    public Result<?> deleteAdmin(@PathVariable Integer id){
        boolean update = adminService.removeById(id);
        return update?
                Result.success("删除成功！"):
                Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()),"删除失败！");

    }


    /*
            这几个控制器方法可以写在其他控制器类中的，不然太臃肿
            1、查询所有的角色
            2、查询操作员所携带的角色：上面控制器已经完成
            3、更新操作员的角色
     */


    @ApiOperation(value = "获取所有角色")
    @GetMapping("/roles")
    public Result<?> getAllRoles(){
        return Result.success(roleService.list());
    }

    @ApiOperation(value = "更新操作员角色")
    @PutMapping("/role")
    public Result<?> updateAdminRole(Integer adminId,Integer[] rids){

        try {
            return adminService.updateAdminRole(adminId,rids);
        } catch (SQLException throwables) {
            log.error("发生了数据库异常，数据库开始回滚：{}",throwables.getMessage());
            return Result.error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "更新失败");
        }

    }





}
